package com.swh.controller;

import com.alibaba.fastjson.JSONObject;
import com.swh.entity.User;
import com.swh.servic.UserServic;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.UUID;

@WebServlet("/qq_login")
public class QQLoginServlet extends HttpServlet {

    // qq回调地址
    private String baseUrl = "http://xb.dfbz.com/qq_login";
    private UserServic userService = new UserServic();

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) {
        try {
            HttpSession session = request.getSession();

            // 获取认证成功后的code
            String code = request.getParameter("code");

            // 在QQ互联申请的appid以及key
            String appid = "101837854";
            String appkey = "0ce88a9308a820ddf5bc28fdf0becd74";

            String url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code" + "&client_id=" + appid +
                    "&client_secret=" + appkey +
                    "&code=" + code +
                    "&redirect_uri=" + baseUrl;

            // 发送HttpClient请求获取access_token(临时票据)
            String access_token = getAccessToken(url);

            url = "https://graph.qq.com/oauth2.0/me?access_token=" + access_token;

            // 获取openid(qq唯一标识符)
            String openid = getOpenID(url);

            url = "https://graph.qq.com/user/get_user_info?access_token=" + access_token +
                    "&oauth_consumer_key=" + appid +
                    "&openid=" + openid;

            // 根据qqOpenid查询此用户原来有没有使用过qq登录
            User user = userService.findByQqOpenid(openid);

            // 说明该用户是第一次使用QQ登录
            if (user == null) {
                // 获取用户信息
                JSONObject jsonObject = getUserInfo(url);

                user = new User();

                // 用户的头像
                user.setPic(jsonObject.getString("figureurl_qq_2"));

                // 用户的昵称
                user.setRealName(jsonObject.getString("nickname"));

                // 随机用户名(11位随机字符串)
//                user.setUsername(UUID.randomUUID().toString().substring(36-15));

                user.setQqOpenid(openid);
                // 注册一个新的用户
                userService.save(user);

//                user=userService.findByQqOpenid(openid);
            }

            // 修改登录时间
            userService.updateLoginTime(user.getId());

            session.setAttribute("login", user);
            response.sendRedirect("/html/home.jsp");

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private static JSONObject getUserInfo(String url) throws IOException {
        JSONObject jsonObject = null;
        CloseableHttpClient client = HttpClients.createDefault();

        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();


        if (entity != null) {
            String result = EntityUtils.toString(entity, "UTF-8");
            jsonObject = JSONObject.parseObject(result);
        }

        httpGet.releaseConnection();

        return jsonObject;
    }

    /**
     * 根据url通过HttpClient请求返回AccessToken
     *
     * @param url
     * @return
     * @throws Exception
     */
    private String getAccessToken(String url) throws Exception {
        // 创建一次HttpClient请求
        CloseableHttpClient client = HttpClients.createDefault();
        String token = null;

        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            String result = EntityUtils.toString(entity, "UTF-8");
            if (result.indexOf("access_token") >= 0) {
                String[] array = result.split("&");
                for (String str : array) {
                    if (str.indexOf("access_token") >= 0) {
                        token = str.substring(str.indexOf("=") + 1);
                        break;
                    }
                }
            }
        }

        httpGet.releaseConnection();
        return token;

    }


    public static String getOpenID(String url) throws IOException {
        JSONObject jsonObject = null;
        CloseableHttpClient client = HttpClients.createDefault();

        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            String result = EntityUtils.toString(entity, "UTF-8");
            jsonObject = parseJSONP(result);
        }

        httpGet.releaseConnection();

        if (jsonObject != null) {
            return jsonObject.getString("openid");
        } else {
            return null;
        }
    }

    private static JSONObject parseJSONP(String jsonp) {
        int startIndex = jsonp.indexOf("(");
        int endIndex = jsonp.lastIndexOf(")");

        String json = jsonp.substring(startIndex + 1, endIndex);

        return JSONObject.parseObject(json);
    }
}
